package com.example.demo.localcache.support;

import java.util.Observable;
import java.util.Observer;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname AbstractLazyCacheSupport
 * @description 支持缓存懒加载
 * @date 2024/01/24 15:33
 * <p>
 * ******************************************************
 */
public abstract class AbstractLazyCacheSupport extends Observable {

    /**
     * 缓存管理观察者
     */
    protected Observer cacheManagerObserver;

    /**
     * 是否已经初始化
     *
     * @return 是否已经初始化
     */
    protected abstract boolean alreadyInitCache();

    /**
     * 懒加载策略初始化缓存
     */
    protected void lazyInitIfNeed() {
        if (alreadyInitCache()) {
            return;
        }

        // 单点代码显式锁
        synchronized (AbstractLazyCacheSupport.class) {

            // 再次检查是否已经初始化
            if (alreadyInitCache()) {
                return;
            }

            this.addObserver(cacheManagerObserver);
            this.setChanged();
            this.notifyObservers();
        }
    }

    /**
     * Setter method for property <tt>cacheManagerObserver</tt>.
     *
     * @param cacheManagerObserver value to be assigned to property cacheManagerObserver
     */
    public void setCacheManagerObserver(Observer cacheManagerObserver) {
        this.cacheManagerObserver = cacheManagerObserver;
    }

}
